package ore.example.pokemonPb.GUI;

import com.pixelmonmod.pixelmon.api.pokemon.Pokemon;
import com.pixelmonmod.pixelmon.api.pokemon.PokemonFactory;
import com.pixelmonmod.pixelmon.api.pokemon.species.Species;
import com.pixelmonmod.pixelmon.api.registries.PixelmonSpecies;
import com.pixelmonmod.pixelmon.api.storage.PCStorage;
import com.pixelmonmod.pixelmon.api.storage.PlayerPartyStorage;
import com.pixelmonmod.pixelmon.api.storage.StorageProxy;
import com.pixelmonmod.pixelmon.api.util.helpers.SpriteItemHelper;
import ore.example.pokemonPb.item.CountItem;
import ore.example.pokemonPb.utils.RewardData;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.craftbukkit.v1_21_R1.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import xyz.xenondevs.invui.gui.Gui;
import xyz.xenondevs.invui.gui.PagedGui;
import xyz.xenondevs.invui.gui.structure.Markers;
import xyz.xenondevs.invui.item.Item;
import xyz.xenondevs.invui.item.ItemProvider;
import xyz.xenondevs.invui.item.builder.ItemBuilder;
import xyz.xenondevs.invui.item.impl.AbstractItem;
import xyz.xenondevs.invui.item.impl.SimpleItem;
import xyz.xenondevs.invui.item.impl.controlitem.PageItem;
import xyz.xenondevs.invui.window.Window;

import java.util.*;

public class PokedexGUI {

    // 上一页按钮
    public static class BackItem extends PageItem {
        public BackItem() {
            super(false);
        }

        @Override
        public ItemProvider getItemProvider(PagedGui<?> gui) {
            return new ItemBuilder(Material.RED_STAINED_GLASS_PANE)
                    .setDisplayName("§c上一页")
                    .addLoreLines(gui.hasPreviousPage()
                            ? "§7当前页: §e" + (gui.getCurrentPage() + 1)
                            : "§8已经是第一页");
        }
    }

    // 下一页按钮
    public static class ForwardItem extends PageItem {
        public ForwardItem() {
            super(true);
        }

        @Override
        public ItemProvider getItemProvider(PagedGui<?> gui) {
            return new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE)
                    .setDisplayName("§a下一页")
                    .addLoreLines(gui.hasNextPage()
                            ? "§7跳转至 §e" + (gui.getCurrentPage() + 2)
                            : "§8已经是最后一页");
        }
    }

    // 打开 GUI
    public static void openPokedex(Player player, int generation) {
        PlayerPartyStorage party = StorageProxy.getPartyNow(player.getUniqueId());
        PCStorage pc = StorageProxy.getPCForPlayerNow(player.getUniqueId());

        Item border = new SimpleItem(
                new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setDisplayName("")
        );
        List<Item> pokemonItems = new ArrayList<>();

        Set<Integer> excluded = Set.of(2000, 2008); // 排除的编号
        int ownedCount = 0;
        int totalCount = 0;

        // 生成该世代的所有宝可梦
        for (int dexNumber : PixelmonSpecies.getGenerationDex(generation)) {
            if (excluded.contains(dexNumber)) continue;
            Species species = PixelmonSpecies.fromNationalDex(dexNumber);
            if (species == null) continue;
            totalCount++;

            Pokemon pokemon = PokemonFactory.create(species);
            if (pokemon == null) continue;

            // 检查是否已拥有
            boolean owned = Arrays.stream(party.getAll())
                    .filter(Objects::nonNull)
                    .anyMatch(p -> p.getSpecies() == species)
                    || Arrays.stream(pc.getAll())
                    .filter(Objects::nonNull)
                    .anyMatch(p -> p.getSpecies() == species);

            if (owned) ownedCount++;

            try {
                net.minecraft.world.item.ItemStack nms = SpriteItemHelper.getPhoto(pokemon);
                ItemStack item = CraftItemStack.asBukkitCopy(nms);
                String desc = species.getDescTranslation().getString();

                ItemBuilder builder = new ItemBuilder(item)
                        .setDisplayName((owned ? "§a" : "§e") + "#" + dexNumber + " " + pokemon.getLocalizedName())
                        .addLoreLines(
                                "§7" + desc,
                                "§6世代: 第" + generation + "世代",
                                "",
                                owned ? "§a收集状态: 已拥有" : "§c收集状态: 未捕获"
                        );

                if (owned) {
                    builder.addEnchantment(Enchantment.PROTECTION, 1, true)
                            .addItemFlags(ItemFlag.HIDE_ENCHANTS);
                }

                pokemonItems.add(new SimpleItem(builder));

            } catch (Exception e) {
                Bukkit.getLogger().warning("[PokemonPb] 图鉴生成出错: " + species.getName() + " -> " + e.getMessage());
            }
        }

        boolean allCollected = ownedCount == totalCount;
        boolean hasClaimed = RewardData.hasClaimed(player.getUniqueId(), generation);

        FileConfiguration cfg = Bukkit.getPluginManager().getPlugin("PokemonPb").getConfig();
        String cmd = cfg.getString("rewards.command", "give %player% diamond 1");
        String msg = cfg.getString("rewards.message", "§a你领取了图鉴完成奖励！");
        String soundName = cfg.getString("rewards.sound", "ENTITY_PLAYER_LEVELUP");

        // ✅ 直接交给 CountItem 管理点击逻辑（无需 canClaim）
        CountItem countItem = new CountItem(player, cmd, msg, soundName, ownedCount, totalCount, generation);

        Gui gui = PagedGui.items()
                .setStructure(
                        "# # # # # # # # #",
                        "# x x x x x x x #",
                        "# x x x x x x x #",
                        "# x x x x x x x #",
                        "# x x x x x x x #",
                        "# # # < c > # # #"
                )
                .addIngredient('#', border)
                .addIngredient('x', Markers.CONTENT_LIST_SLOT_HORIZONTAL)
                .addIngredient('<', new BackItem())
                .addIngredient('>', new ForwardItem())
                .addIngredient('c', countItem)
                .setContent(pokemonItems)
                .build();

        Window window = Window.single()
                .setViewer(player)
                .setTitle("§a第" + generation + "世代宝可梦图鉴")
                .setGui(gui)
                .build();

        window.open();
    }
}
